package org.groupg.practice;

import org.jgroups.*;
import org.jgroups.blocks.*;
import org.jgroups.util.Util;

import java.io.*;

public class StateTransferExample implements Receiver {
    private JChannel channel;
    private String state = "Initial state";

    public static void main(String[] args) throws Exception {
        new StateTransferExample().start();
    }

    private void start() throws Exception {
        channel = new JChannel();
        channel.setReceiver(this);
        channel.connect("StateTransferCluster");

        // 模拟状态更新
        for (int i = 0; i < 10; i++) {
            state = "State " + i;
            Thread.sleep(5000);
        }

        channel.close();
    }

    @Override
    public void getState(OutputStream output) throws Exception {
        synchronized(state) {
            Util.objectToStream(state, new DataOutputStream(output));
        }
    }

    @Override
    public void setState(InputStream input) throws Exception {
        String newState = (String)Util.objectFromStream(new DataInputStream(input));
        synchronized(state) {
            state = newState;
        }
        System.out.println("Received new state: " + state);
    }

    @Override
    public void viewAccepted(View view) {
        System.out.println("View changed: " + view);
    }
}